package com.leetcode.根据算法进行分类.字符串查找算法相关;

/**
 * @author: ZhouBert
 * @date: 2020/12/16
 * @description: 剑指 Offer 05. 替换空格
 * https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
 */
public class A_剑指_Offer_05_替换空格 {

	public String replaceSpace(String s) {
		//边界判断
		if (s == null || s.isEmpty()) {
			return s;
		}
		StringBuilder sb =new StringBuilder();
		char[] chars = s.toCharArray();
		for (int i = 0; i < chars.length; i++) {
			if (chars[i]==' '){
				sb.append("%20");
			}else {
				sb.append(chars[i]);
			}
		}
		return sb.toString();
	}

	/**
	 * 数组拷贝的方式很奇特！
	 * 应该更加省空间！省时间！
	 * TODO:用数组的方案简直就是神技！
	 * @param s
	 * @return
	 */
	public String replaceSpace2(String s){
		int length = s.length();
		char[] array = new char[length * 3];
		int size = 0;
		for (int i = 0; i < length; i++) {
			char c = s.charAt(i);
			if (c == ' ') {
				array[size++] = '%';
				array[size++] = '2';
				array[size++] = '0';
			} else {
				array[size++] = c;
			}
		}
		//TODO
		String newStr = new String(array, 0, size);
		return newStr;
	}

	public static void main(String[] args) {

	}
}
